#include "./status_task.h"
#include "../driver/motor.h"
#include "../driver/music_uart.h"
#include "../driver/log_uart.h"
#include "../driver/key.h"
#include "../driver/motor.h"
#include "./work_task.h"
#include "../service/device_info.h"
#include "../driver/cmd_uart.h"

namespace task {

using namespace driver;
using namespace service;

static uint8_t motor_err = 0;
static uint32_t next_send_tick = 10 * 60 * 1000;
static uint32_t once_upload_duration = 5 * 60 * 60 * 1000;

static const uint8_t version = 0x01;

void StatusTask_t::run() {

    for (;;) {
        update();
        osDelay(500);
    }
}

void StatusTask_t::update() {
    bool changed = false;

    uint8_t tmp = motor->status();
    if (motor_err != tmp) {
        motor_err = tmp;
        changed = true;
    }

    if (osKernelGetTickCount() >= next_send_tick) {
        changed = true;
        next_send_tick += once_upload_duration;
    }

    if (changed) {
        send_status();
    }
}

void StatusTask_t::send_status() {
    uint32_t sweet_count = deviceInfo->sweet_count;
    uint32_t price_sum = deviceInfo->price_sum;

    uint8_t buf[] = {
        0x2b, 0x1b,
        motor_err, 0,
        workTask->drop_flag(), 0, 0,
        version,
        sweet_count >> 16, sweet_count >> 8, sweet_count,
        0, 0, 0,
        price_sum >> 16, price_sum >> 8, price_sum,
        0, 0, 0, 0, 0, 0,
        0,
        deviceInfo->price,
        0x0D, 0x0A
    };
    cmdUart->write(buf, sizeof (buf));
}

}
